<template>
  <el-form
      ref="registryRefForm"
      :model="registryForm"
      :rules="rules"
      label-width="auto"
      :label-position="labelPosition"
      :size="size"
  >
    <el-form-item label="账号" prop="userName">
      <el-input type="text" v-model="registryForm.userName" placeholder="请输入账号"/>
    </el-form-item>
    <el-form-item label="密码" prop="passWord">
      <el-input type="password" v-model="registryForm.passWord" placeholder="请输入密码"/>
    </el-form-item>
    <el-form-item label="重输密码" prop="confirmPassword">
      <el-input type="password" v-model="registryForm.confirmPassword" placeholder="请输入密码"/>
    </el-form-item>
    <div style="width:100%" class="myFlex-x">
      <el-form-item>
        <el-button type="primary" @click="submitForm">立即注册</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </div>
  </el-form>
</template>

<script setup lang="ts">
import {ref} from "vue"
import {ElMessage} from "element-plus";
import request from "@/utils/request";
//从父组件中获取传来的函数
const emit = defineEmits(['close-dialog'])
let registryRefForm = ref()
let labelPosition = ref('left')
const size = ref('large')
let registryForm = ref({
  userName: '',
  passWord: '',
  confirmPassword: ''
})
let rules={
  userName:[
    { required: true, message: '请输入账号', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]{5,12}$/,message: '账号必须由数字和英文字母5-12位组成',trigger: 'blur' }
  ],
  passWord:[
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]{5,12}$/,message: '密码必须由数字和英文字母5-12位组成',trigger: 'blur' }
  ],
  confirmPassword:[
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]{5,12}$/,message: '密码必须由英文字母5-12位组成',trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== registryForm.value.passWord) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      }
    }
  ]
}
//点击重置
function resetForm() {
  registryRefForm.value.resetFields();
}
//点击登录
function submitForm() {
  registryRefForm.value.validate(valid => {
    if (valid) {
      //发送注册请求，将用户输入的账号和密码发送给后端，将数据提交到数据库，然后后端响应数据给前端，这种请求是post请求
      request.post('/registry', registryForm.value)
          .then(res => {
            let result = res.data;
            switch (result){
              case 1:
                ElMessage.success('注册成功')
                emit('close-dialog')
                break;
              case 0:
                ElMessage.error('用户已存在')
                break;
              case -1:
                ElMessage.error('注册失败')
                break;
            }
          })
          // .catch(err => {
          //   ElMessage.error("请求失败")
          // })
    }else {
      ElMessage.error('注册失败')
    }
  })
}
</script>

<style scoped>

</style>